package linearstructure.sparsearray;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-21 18:47
 * @ Description : 稀疏矩阵
 */
public class SparseArray
{
    public static void main(String[] args)
    {
        //创建原始矩阵 11*11
        //0: 没有棋子;1: 黑子; 2: 蓝子
        int[][] chessArray = new int[11][11];
        chessArray[0][0] = 2;
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        //输出原始矩阵
        System.out.println("原始矩阵为:");
        for (int[] row : chessArray)
        {
            for (int data : row)
            {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        //转为稀疏数组
        //1. 遍历二维数组,获得非0数据个数
        int sum = 0;
        for (int i = 0; i < 11; i++)
        {
            for (int j = 0; j < 11; j++)
            {
                if (chessArray[i][j] != 0)
                {
                    sum++;
                }
            }
        }

        //2. 创建对应的稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        //给稀疏数组的第一行赋值
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        //遍历二维数组,将不为0的值存入稀疏数组
        int count = 0;
        for (int i = 0; i < 11; i++)
        {
            for (int j = 0; j < 11; j++)
            {
                if (chessArray[i][j] != 0)
                {
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chessArray[i][j];
                }
            }
        }

        //输出稀疏数组
        System.out.println("对应的稀疏数组为:");
        for (int[] row : sparseArray)
        {
            System.out.printf("%d\t%d\t%d\t\n", row[0], row[1],
                    row[2]);
        }

        //持久化稀疏数组
        new IO().save(sparseArray);

        //恢复为原始数组
        int[][] newChess = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++)
        {
            newChess[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("恢复后的矩阵为:");
        for (int[] row : newChess)
        {
            for (int data : row)
            {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }

}
